package com.example.min.restappmobile;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Created by Alexander on 29.03.2015.
 */
public class MainActivity extends Activity {

    private final String EMPTY_S = "";
    private TextView lblName;
    private TextView lblLastName;
    private TextView lblMiddleName;
    private TextView lblBirthDate;
    private TextView lblSalary;
    private TextView lblStartWorkDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getOverflowMenu();
        setContentView(R.layout.main_layout);

        lblName = (TextView) findViewById(R.id.lblName);
        lblLastName = (TextView) findViewById(R.id.lblLastName);
        lblMiddleName = (TextView) findViewById(R.id.lblMiddleName);
        lblBirthDate = (TextView) findViewById(R.id.lblBirthDate);
        lblSalary = (TextView) findViewById(R.id.lblSalary);
        lblStartWorkDate = (TextView) findViewById(R.id.lblStartWorkDate);

        final Object mutex = new Object();

        final String userLogin = Session.getSessionItem("login");
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                String serverUrl = getString(R.string.api_server);
                HttpGet httpGet = new HttpGet(serverUrl + "/api/accountapi?userLogin=" + userLogin );
                HttpResponse response;
                try {
                    response = httpClient.execute(httpGet);
                    String stringResponse = new BasicResponseHandler().handleResponse(response);
                    final JSONObject json = new JSONObject(stringResponse);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Session.setSessionItem("userId", json.getString("id"));
                                lblName.setText(json.getString("name"));
                                lblLastName.setText(json.getString("lastName"));
                                lblMiddleName.setText(json.getString("middleName"));
                                lblBirthDate.setText(json.getString("dateBirth"));
                                lblSalary.setText(json.getString("salary"));
                                lblStartWorkDate.setText(json.getString("startWorkDate"));
                            } catch(Exception ex) {
                                Toast.makeText(getApplicationContext(), "Во время отображения данных произошла ошибка", Toast.LENGTH_SHORT).show();
                            }
                        }

                    });
                } catch(Exception ex) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "Извините, произошла ошибка", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                synchronized (mutex) {
                    mutex.notifyAll();
                }
            }
        }).start();

        synchronized (mutex) {
            try {
                mutex.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }



    private void getOverflowMenu() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if(menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_items, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.graphic:
                Toast.makeText(this, "Graphic", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.factWork:
                Toast.makeText(this, "Fact of work", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.employeeList:
                Toast.makeText(this, "employee list", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return  true;
        }
    }
}
